package com.bobby.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @Description TODO
 * @Date 2020/8/12 20:51
 * @Created wenjunpei
 */
public class JdbcUtils {

    private static DruidDataSource druidDataSource;

    private static ThreadLocal<Connection> conns = new ThreadLocal<>();

    static {
        try {
            InputStream resourceAsStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            Properties properties = new Properties();
            properties.load(resourceAsStream);
            druidDataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    public static Connection getConnection(){
        Connection connection = conns.get();
        if(connection == null) {
            try {
                connection = druidDataSource.getConnection();
                // 保存到Threadlocal对象中，供后面的jdbc操作使用
                conns.set(connection);
                // 设置为手动管理事务
                connection.setAutoCommit(false);

            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }

    public static void commitAndClose() {
        Connection connection = conns.get();
        if(connection != null ) {
            try {
                connection.commit();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        //一定要执行remove操作， 否则就会出错。(因为Tomcat 服务器底层使用了线程池技术)
        conns.remove();
    }

    public static void rollbackAndClose() {
        Connection connection = conns.get();
        if(connection != null) {
            try {
                connection.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        //一定要执行remove操作， 否则就会出错。(因为Tomcat 服务器底层使用了线程池技术)
        conns.remove();
    }

//    public static void close(Connection connection) {
//        if(connection != null) {
//            try {
//                connection.close();
//            } catch (SQLException e) {
//                e.printStackTrace();
//            }
//        }
//    }
}
